//
//  MediaPlayerViewController.m
//  HaoHint
//
//  Created by winter on 16/6/4.
//  Copyright © 2016年 wd. All rights reserved.
//

#import "MediaPlayerViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "SGWiFiUploadManager.h"

#define kLocalFileKey @"localFile"

@interface MediaPlayerModel : NSObject
@property (nonatomic, copy) NSString *fileName;
@property (nonatomic, copy) NSString *filePath;

@property (nonatomic, copy) NSString *realFilePath;
@end

@implementation MediaPlayerModel

- (instancetype)initWithDict:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
        _fileName = [[dict allKeys] firstObject];
        _filePath = dict[_fileName];
    }
    return self;
}

- (NSString *)realFilePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
    NSString *libPath = [paths objectAtIndex:0];
    
    NSString *filePath = [[self.filePath componentsSeparatedByString:@"Library/"] lastObject];
    return [libPath stringByAppendingPathComponent:filePath];
}

@end

@interface MediaPlayerViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray *dataDictArray;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, weak) UITableView *tableView;
@end

@implementation MediaPlayerViewController

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    self.tableView.frame = self.view.bounds;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"本地文件";
    [self setupNavBarItem];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:tableView];
    tableView.delegate = self;
    tableView.dataSource = self;
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
    self.tableView = tableView;
    
    [self loadLocalFile];
}

- (void)setupNavBarItem
{
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(navigationBarAction:)];
    leftItem.tag = 100;
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"WiFi上传" style:UIBarButtonItemStylePlain target:self action:@selector(navigationBarAction:)];
    rightItem.tag = 101;
    
    [self.navigationItem setRightBarButtonItem:rightItem];
    [self.navigationItem setLeftBarButtonItem:leftItem];
}

- (void)navigationBarAction:(UIBarButtonItem *)sender
{
    if (100 == sender.tag) {
        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    else {
        // WiFi
        [self setupWiFiServer];
    }
}

- (void)setupWiFiServer
{
    __weak typeof(self) weakSelf = self;
    SGWiFiUploadManager *mgr = [SGWiFiUploadManager sharedManager];
    BOOL success = [mgr startHTTPServerAtPort:10086];
    if (success) {
        [mgr setFileUploadStartCallback:^(NSString *fileName, NSString *savePath) {
            NSLog(@"File %@ Upload Start", fileName);
            [weakSelf downloadingFileWith:fileName];
        }];
        [mgr setFileUploadProgressCallback:^(NSString *fileName, NSString *savePath, CGFloat progress) {
            NSLog(@"File %@ on progress %f", fileName, progress);
        }];
        [mgr setFileUploadFinishCallback:^(NSString *fileName, NSString *savePath) {
            NSLog(@"File Upload Finish %@ at %@", fileName, savePath);
            [weakSelf addFilePathWith:savePath fileName:fileName];
        }];
    }
    [mgr showWiFiPageFrontViewController:self dismiss:^{
        [mgr stopHTTPServer];
    }];
}

#pragma mark - private method

- (BOOL)containsThisFile:(NSString *)filePath
{
    for (MediaPlayerModel *model in self.dataArray) {
        if ([model.filePath isEqualToString:filePath]) {
            return YES;
        }
    }
    return NO;
}

- (void)addFilePathWith:(NSString *)filePath fileName:(NSString *)fileName
{
    [self finishDownloadFileWith:fileName];
    
    if ([self containsThisFile:filePath]) {
        return;
    }
    
    NSDictionary *dict = @{fileName:filePath};
    [self.dataDictArray addObject:dict];
    [self saveDownloadFile];
    
    MediaPlayerModel *model = [[MediaPlayerModel alloc] initWithDict:dict];
    [self.dataArray addObject:model];
    
    [self.tableView reloadData];
}

- (void)deleteFileWith:(NSInteger)index
{
    MediaPlayerModel *model = [self.dataArray objectAtIndex:index];
    [self removeFileWith:model.realFilePath];
    [self.dataArray removeObject:model];
    [self.dataDictArray removeObjectAtIndex:index];
    [self saveDownloadFile];
}

- (void)removeFileWith:(NSString *)filePath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    [fileManager removeItemAtPath:filePath error:&error];
    
    if (error) {
        NSLog(@"delete fail = %@",error);
    }
    else [NSObject showHudTipStr:@"删除成功！"];
}

- (void)downloadingFileWith:(NSString *)fileName
{
    NSString *tip = [NSString stringWithFormat:@"正在下载，请等待..."];
    [kKeyWindow beginLoadingWithTip:tip];
}

- (void)finishDownloadFileWith:(NSString *)fileName
{
    [kKeyWindow endLoading];
    
    NSString *tip = [NSString stringWithFormat:@"下载完成..."];
    [NSObject showHudTipStr:tip];
}

- (void)loadLocalFile
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSArray *array = [userDefaults objectForKey:kLocalFileKey];
    if (array) {
        [self.dataDictArray addObjectsFromArray:array];
        for (NSDictionary *dict in self.dataDictArray) {
            MediaPlayerModel *model = [[MediaPlayerModel alloc] initWithDict:dict];
            [self.dataArray addObject:model];
        }
    }
}

- (void)saveDownloadFile
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:self.dataDictArray forKey:kLocalFileKey];
    [userDefaults synchronize];
}


// 打开本地视频
- (void)playerMedia:(NSString *)filePath
{
    NSString *s = [[filePath componentsSeparatedByString:@"."] lastObject];
    NSString *lString = [s lowercaseString];
    
    BOOL canPlay = [lString isEqualToString:@"mp4"] || [lString isEqualToString:@"mov"] || [lString isEqualToString:@"3gp"] || [lString isEqualToString:@"mpv"];
    if (!canPlay) {
        [NSObject showHudTipStr:@"该文件暂不支持播放"];
        return;
    }
    NSURL *mediaURL = [NSURL fileURLWithPath:filePath];
    //    MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:mediaURL];
    MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc]initWithContentURL:mediaURL];
    [self presentMoviePlayerViewControllerAnimated:playerVC];
}

#pragma mark - tableview delegate & datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    MediaPlayerModel *model = self.dataArray[indexPath.row];
    cell.textLabel.text = model.fileName;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MediaPlayerModel *model = self.dataArray[indexPath.row];
    [self playerMedia:model.realFilePath];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (UITableViewCellEditingStyleDelete == editingStyle) {
        [self deleteFileWith:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:YES];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

#pragma mark - getter

- (NSMutableArray *)dataDictArray
{
    if (!_dataDictArray) {
        _dataDictArray = [NSMutableArray array];
    }
    return _dataDictArray;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

@end
